package org.zxy.auth.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zxy.auth.context.LoginContext;
import org.zxy.auth.mapper.RolePermissionMapper;
import org.zxy.base.annotation.RonghuaPermission;
import org.zxy.org.domain.Employee;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("TOKEN");
        if (token == null) {// 没有token当前未登录
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        Employee employee = LoginContext.context.get(token);
        if (employee == null) {// 当前登录用户为空，说明当前未登录
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RonghuaPermission annotation = method.getAnnotation(RonghuaPermission.class);
        if (annotation != null) {
            List<String> permissionSn = rolePermissionMapper.getPermissionSnByEmpId(employee.getId());
            String methodName = method.getName();
            Class<?> beanType = handlerMethod.getBeanType();
            String className = beanType.getSimpleName();
            if (permissionSn.contains(className + ":" + methodName)) {
                return true;
            } else {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("{\"success\":false,\"msg\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
